import {
	addOrder,
	Login,
	getHistoryOrders,
	getUserInfor
} from '~/api/index'
import { 
		parseTime
	} from "@/utils/tool.js"
const useSystemStore = defineStore("system", {
	state: () => ({
		//激活菜单
		activeMenuIndex:0,
		//订单详情
		orderList: [],
		//我的订单
		myOrders:[],
		//主题
		dataTheme:'dark',
		//搜索关键词
		searchWord:'',
		//用户信息
		userInfo:{
			phone:''
		}
	}),

	actions: {
		
		//登录
		login(phone){
			
			return new Promise(async(resolve,reject)=>{
				let _re=await Login({phone})
				if(_re.code==200)
				{
					this.userInfo= {phone}
					uni.setStorageSync("userInfo", this.userInfo);
					uni.setStorageSync("token", _re.token);
					resolve(_re)
					getUserInfor({phone}).then(data=>{
						
						this.userInfo=data.data
						uni.setStorageSync("userInfo", this.userInfo);
						 
					})
				}
				else
					reject(_re)
				
			}) 
		},
		//提交订单
		confirmOrders(allMoney){ 
			return new Promise(async (resolve, reject) => {
				setTimeout(async()=>{
					let _pra={ 
						phone:this.userInfo.phone,
						producJson:JSON.stringify(this.orderList) ,
						money:allMoney,
						dateTime:parseTime(new Date())
					}
					let _re = await addOrder(_pra)
		 
					resolve({
						success: true,
					});
					
					getHistoryOrders({phone:this.userInfo.phone}).then(data => {
						this.myOrders = data.data 
					})
				},1300)
				
			}).catch((error) => {
				reject(error);
			});
		},
		//新增订单
		addOrder(data) {
			return new Promise(async (resolve, reject) => {
				if (this.orderList.length == 0) {
					this.orderList.push(data)
				} else {
					let _temp = this.orderList.find(row => row.id == data.id)
					if (_temp)
						_temp.count += 1
					else
						this.orderList.push(data)
				}
				resolve({ 
					success: true,
				});
			}).catch((error) => {
				reject(error);
			});
		},
		//删除订单
		delOrder(data)
		{
			return new Promise(async (resolve, reject) => {
				let _index=this.orderList.findIndex(row=>row.id==data.id)
				this.orderList.splice(_index,1)
				resolve({ 
					success: true,
				});
			}).catch((error) => {
				reject(error);
			});
		},
	},
});

export default useSystemStore;